<template>
    <div class="note">
        <div class="note-section">
            <div class="note-title">今日笔记</div>
            <div v-if="isLoadingToday" class="loading">加载中...</div>
            <div v-else-if="todayNotes.length === 0" class="no-notes">
                今天还没有笔记哦
            </div>
            <div v-else class="note-image today-note-image waterfall-container">
                <div
                    v-for="(note, noteIndex) in todayNotes"
                    :key="noteIndex"
                    class="note-item"
                >
                    <div
                        v-for="(file, fileIndex) in note.fileList"
                        :key="fileIndex"
                        class="image-container waterfall-item"
                    >
                        <img
                            :src="BaseUrl + file.filePath"
                            :alt="note.description"
                            @load="onImageLoad('today')"
                        />
                        <div class="overlay">
                            <p>{{ note.description }}</p>
                            <button
                                class="learn-more"
                                @click="
                                    imgFullMethods({
                                        ...file,
                                        description: note.description,
                                        title: note.title,
                                        noteId: note.id,
                                    })
                                "
                            >
                                了解更多
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="note-section">
            <div class="note-title">
                <el-button
                    @click="goToFirstPage"
                    :disabled="pageNum === 1"
                    v-show="earlyNotes.length !== 0"
                    >第一页</el-button
                >
                <el-button
                    @click="changePageUp"
                    :disabled="pageNum === 1"
                    v-show="earlyNotes.length !== 0"
                    >上一页({{ pageNum }})</el-button
                >
                <span class="note-title-span">早期笔记</span>
                <el-button
                    @click="changePageDown"
                    :disabled="isLastPage"
                    v-show="earlyNotes.length !== 0"
                >
                    {{ isLastPage ? "最后一页" : `下一页(${pageNum + 1})` }}
                </el-button>
                <el-input
                    v-model.number="inputPageNum"
                    placeholder="输入页码"
                    type="number"
                    @keyup.enter="goToInputPage"
                    v-show="earlyNotes.length !== 0"
                />
            </div>
            <div v-if="isLoadingEarly" class="loading">加载中...</div>
            <div v-else-if="earlyNotes.length === 0" class="no-notes">
                暂无早期笔记
            </div>
            <div v-else class="note-image early-note-image waterfall-container">
                <div
                    v-for="(note, noteIndex) in earlyNotes"
                    :key="noteIndex"
                    class="note-item"
                >
                    <div
                        v-for="(file, fileIndex) in note.fileList"
                        :key="fileIndex"
                        class="image-container waterfall-item"
                    >
                        <img
                            :src="BaseUrl + file.filePath"
                            :alt="note.description"
                            @load="onImageLoad('early')"
                        />
                        <div class="overlay">
                            <p>{{ note.description }}</p>
                            <button
                                class="learn-more"
                                @click="
                                    imgFullMethods({
                                        ...file,
                                        description: note.description,
                                        title: note.title,
                                        noteId: note.id,
                                    })
                                "
                            >
                                了解更多
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 模态框 -->
        <div v-if="showModal" class="modal" @click="showModal = false">
            <div class="modal-content" @click.stop>
                <div class="modal-content-header">
                    <p class="title">{{ currentFullImage.title }}</p>

                    <div class="deal">
                        <img
                            class="download"
                            src="/icons/download.png"
                            alt="下载"
                            @click="downloadImage(currentFullImage)"
                        />

                        <img
                            class="cancel"
                            src="/icons/cancel.png"
                            alt="取消"
                            @click="showModal = false"
                        />
                    </div>
                </div>

                <img
                    class="fullImage"
                    :src="currentFullImage.imgSrc"
                    :alt="currentFullImage.description"
                />
                <p class="description">
                    <i>{{ currentFullImage.description }}</i>
                </p>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useStore } from "vuex";
import {
    BaseUrl,
    getEarlyNoteFilesList,
    getTodayNoteFilesList,
} from "../../../server/userApi";

import axios from "axios";

const store = useStore();

const showModal = ref(false);
const currentFullImage = ref(null);
const loadedTodayImages = ref(0);
const loadedEarlyImages = ref(0);
const isLoadingToday = ref(true);
const isLoadingEarly = ref(true);
const pageNum = ref(1);
const userId = store.state.userInfo.id;
const isLastPage = ref(false);
const previousEarlyNotes = ref([]);
const inputPageNum = ref("");
const maxPageNum = ref(1);

const imgFullMethods = (item) => {
    console.log(item);
    currentFullImage.value = {
        imgSrc: item.filePath ? BaseUrl + item.filePath : item.imgSrc,
        title: item.title,
        description: item.description,
    };
    showModal.value = true;
    // console.log(currentFullImage.value);
};

const todayNotes = ref([]);
const earlyNotes = ref([]);

const noteRow = 5; // 统一行数

const createWaterfall = (containerSelector, columnCount) => {
    const containers = document.querySelectorAll(containerSelector);
    containers.forEach((container) => {
        if (!container) return;
        const items = container.querySelectorAll(".waterfall-item");
        const columnHeights = new Array(columnCount).fill(0);

        items.forEach((item) => {
            const minHeight = Math.min(...columnHeights);
            const index = columnHeights.indexOf(minHeight);

            item.style.position = "absolute";
            item.style.left = `${index * (100 / columnCount)}%`;
            item.style.top = `${minHeight}px`;
            item.style.width = `${100 / columnCount}%`;

            columnHeights[index] += item.offsetHeight + 10; // 10px为间距
        });

        container.style.height = `${Math.max(...columnHeights)}px`;
    });
};

const updateWaterfalls = () => {
    createWaterfall(".today-note-image", noteRow);
    createWaterfall(".early-note-image", noteRow);
};

const totalTodayImages = computed(() => {
    return todayNotes.value.reduce(
        (total, note) => total + note.fileList.length,
        0
    );
});

const onImageLoad = (type) => {
    if (type === "today") {
        loadedTodayImages.value++;
        if (loadedTodayImages.value === totalTodayImages.value) {
            nextTick(() => {
                createWaterfall(".today-note-image", noteRow);
            });
        }
    } else {
        loadedEarlyImages.value++;
        const totalEarlyImages = earlyNotes.value.reduce(
            (total, note) => total + note.fileList.length,
            0
        );
        if (loadedEarlyImages.value === totalEarlyImages) {
            nextTick(() => {
                createWaterfall(".early-note-image", noteRow);
            });
        }
    }
};

const goToFirstPage = async () => {
    if (pageNum.value !== 1) {
        resetPagination();
        await fetchEarlyNotes();
    } else {
        ElMessage.info("已经是第一页了");
    }
};

const changePageUp = async () => {
    if (pageNum.value > 1) {
        pageNum.value--;
        isLastPage.value = false;
        await fetchEarlyNotes();
    } else {
        ElMessage.info("已经是第一页了");
    }
};

const changePageDown = async () => {
    if (!isLastPage.value) {
        pageNum.value++;
        await fetchEarlyNotes();
    } else {
        ElMessage.info("已经是最后一页了");
    }
};

const goToInputPage = async () => {
    const targetPage = parseInt(inputPageNum.value);
    if (isNaN(targetPage) || targetPage < 1) {
        ElMessage.warning("请输入有效的页码");
        return;
    }

    if (targetPage > maxPageNum.value) {
        ElMessage.warning(`页码不能超过最大页码 ${maxPageNum.value}`);
        return;
    }

    if (targetPage === pageNum.value) {
        ElMessage.info("当前已经是该页");
        return;
    }

    pageNum.value = targetPage;
    isLastPage.value = false;
    await fetchEarlyNotes();
};

const fetchEarlyNotes = async () => {
    try {
        isLoadingEarly.value = true;
        loadedEarlyImages.value = 0; // 重置加载图片计数
        // 默认imageFilter为1 表示只获取图片类型的数据

        const earlyData = await getEarlyNoteFilesList(userId, 1, pageNum.value);
        console.log(earlyData);

        if (earlyData && earlyData.data) {
            if (earlyData.data.length === 0) {
                ElMessage.info(
                    `已经是最后一页了，最大页码为 ${maxPageNum.value}`
                );
                pageNum.value = Math.max(1, pageNum.value - 1); // 确保页码不小于1
                isLastPage.value = true;
                return;
            }

            // 检查新获取的数据是否与上一次的数据相同
            const isDataSame =
                JSON.stringify(earlyData.data) ===
                JSON.stringify(previousEarlyNotes.value);
            if (isDataSame && pageNum.value > maxPageNum.value) {
                ElMessage.info(`页码不能超过最大页码 ${maxPageNum.value}`);
                pageNum.value = maxPageNum.value;
                isLastPage.value = true;
                return;
            }

            earlyNotes.value = earlyData.data;
            previousEarlyNotes.value = earlyData.data; // 保存当前数据以供下次比较

            // 更新最大页码
            if (pageNum.value > maxPageNum.value) {
                maxPageNum.value = pageNum.value;
            }

            isLastPage.value = isDataSame;
        }
    } catch (error) {
        console.error("Error fetching early notes:", error);
        ElMessage.error("获取早期笔记失败");
    } finally {
        isLoadingEarly.value = false;
        await nextTick();
        // 在下一个tick更新瀑布流布局
        nextTick(() => {
            updateWaterfalls();
        });
    }
};

// 重置分页状态的函数
const resetPagination = () => {
    pageNum.value = 1;
    isLastPage.value = false;
    previousEarlyNotes.value = [];
    maxPageNum.value = 1;
    inputPageNum.value = "";
};

watch(earlyNotes, () => {
    nextTick(() => {
        updateWaterfalls();
    });
});

onMounted(async () => {
    window.addEventListener("resize", updateWaterfalls);
    try {
        isLoadingToday.value = true;
        // const todayFileFilter = ref(1);
        const todayData = await getTodayNoteFilesList(userId, 1);

        console.log(todayData);
        if (todayData && todayData.data) {
            todayNotes.value = todayData.data;
        }
    } catch (error) {
        console.error("Error fetching today notes:", error);
        // ElMessage.error("获取今日笔记失败");
    } finally {
        isLoadingToday.value = false;
    }

    resetPagination(); // 重置分页状态
    await fetchEarlyNotes();

    await nextTick();

    updateWaterfalls();
});

onUnmounted(() => {
    window.removeEventListener("resize", updateWaterfalls);
});

// 下载
const downloadImage = async (currentFullImage) => {
   
    try {
        // 使用 axios 获取图片数据
        const response = await axios({
            url: currentFullImage.imgSrc,
            method: "GET",
            responseType: "blob",
        });

        // 创建一个 Blob 对象
        const blob = new Blob([response.data], {
            type: response.headers["content-type"],
        });

        // 创建一个临时 URL
        const url = window.URL.createObjectURL(blob);

        // 创建一个隐藏的 <a> 元素来触发下载
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;

        // 从 imgSrc 中提取文件名
        const fileName = currentFullImage.imgSrc.split("/").pop();
        a.download = fileName;

        // 添加到 body，触发点击，然后移除
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        ElMessage.success("文件下载成功");
    } catch (error) {
        console.error("下载文件时出错:", error);
        ElMessage.error("下载文件失败");
    }
};
</script>

<style lang="scss" scoped>
.note {
    margin-top: 40px;
    width: 100%;
    background-color: white;

    .note-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 40px;

        .note-title {
            height: 50px;
            font-size: 28px;
            padding: 10px;
            text-align: center;
            border-bottom: 2px solid rgb(212, 71, 71);
            margin-bottom: 12px;
            display: flex;
            align-items: center;

            .el-button {
                margin: 0 10px;
                padding: 0 10px;
                border: none;

                &:hover {
                    transform: scale(1.1);
                }
            }

            .el-input {
                width: 100px;
                margin-left: 10px;
                border: none;
                border-bottom: 1px solid rgb(212, 71, 71);
                margin-top: 20px;
                text-align: center;

                :deep(.el-input__wrapper) {
                    box-shadow: none;
                }
            }
        }

        .note-image {
            position: relative;
            width: 90%;

            .image-container {
                position: absolute;
                padding: 10px;
                box-sizing: border-box;
                transition: all 0.3s ease;

                img {
                    width: 100%;
                    height: auto;
                    display: block;
                    transition: transform 0.3s ease;
                    border: 2px solid rgba(0, 0, 0, 0.2);
                    border-radius: 10px;
                }

                .overlay {
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background-color: rgba(0, 0, 0, 0.2);
                    overflow: hidden;
                    width: 100%;
                    height: 0;
                    transition: 0.5s ease;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    color: white;
                }

                &:hover {
                    .overlay {
                        height: 100%;
                        border-radius: 5px;
                    }

                    img {
                        transform: scale(1.1);
                    }
                }

                p {
                    text-align: center;
                    margin-bottom: 10px;
                }

                .learn-more {
                    padding: 10px 20px;
                    background-color: white;
                    color: black;
                    border: none;
                    cursor: pointer;
                    transition: background-color 0.3s ease;

                    &:hover {
                        background-color: #f0f0f0;
                    }
                }
            }
        }
    }
}

.loading,
.no-notes {
    text-align: center;
    padding: 20px;
    font-size: 18px;
    color: #666;
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;

    .modal-content {
        background-color: white;
        padding: 10px;
        border-radius: 8px;
        max-width: 95%;
        max-height: 95%;
        overflow: auto;
        display: flex;
        flex-direction: column;
        // align-items: center;

        .modal-content-header {
            position: relative;

            .title {
                text-align: center;
                margin-bottom: 10px;
            }

            .deal {
                position: absolute;
                top: -10px;
                right: -1px;
                display: flex;
                align-items: center;

                .download {
                    margin-right: 50px;
                    width: 30px;
                    cursor: pointer;
                    &:hover {
                        transform: scale(1.1);
                    }
                }

                .cancel {
                    width: 20px;
                    cursor: pointer;

                    &:hover {
                        transform: scale(1.1);
                    }
                }
            }
        }

        .fullImage {
            max-width: 100%;
            max-height: 80vh;
            object-fit: contain;
        }
        //
        .description {
            margin: 10px auto;
            max-width: 400px;
        }
    }
}
</style>
